/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.admin;

import com.hboxs.asl.entity.DeliveryCenter;
import com.hboxs.asl.entity.DeliveryTemplate;
import com.hboxs.asl.entity.Order;
import com.hboxs.asl.service.DeliveryCenterService;
import com.hboxs.asl.service.DeliveryTemplateService;
import com.hboxs.asl.service.OrderService;
import com.hboxs.asl.util.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;

/**
 * Controller - 打印
 */
@Controller("adminPrintController")
@RequestMapping("/asl-admin/print")
public class PrintController extends BaseController {

    @Resource(name = "orderServiceImpl")
    private OrderService orderService;
    @Resource(name = "deliveryTemplateServiceImpl")
    private DeliveryTemplateService deliveryTemplateService;
    @Resource(name = "deliveryCenterServiceImpl")
    private DeliveryCenterService deliveryCenterService;

    /**
     * 订单打印
     */
    @RequestMapping(value = "/order", method = RequestMethod.GET)
    public String order(Long id, ModelMap model) {
        model.addAttribute("order", orderService.find(id));
        return "/admin/print/order";
    }

    /**
     * excel打印
     */
    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    public void excel(Long id, ModelMap model, HttpServletResponse response) {
        Order order = orderService.find(id);
        model.addAttribute("order", orderService.find(id));
        try {

            InputStream input = this.getClass().getResourceAsStream("/print/print_template.xls");  //建立输入流
            //根据文件格式(2003或者2007)来初始化

            HSSFWorkbook wb = new HSSFWorkbook(input);

            HSSFSheet sheet = wb.getSheetAt(0);     //获得第一个表单



            // 第N个合并单元格 : 收件人，联系电话，地址
            String str_receiver = order.getConsignee() + "  "+ order.getPhone() +"  "  + order.getAreaName()+" " + order.getAddress();
            CellRangeAddress region_receiver = sheet.getMergedRegion(6);
            int colIndex_receiver = region_receiver.getFirstColumn(); // 合并区域首列位置
            int rowNum_receiver = region_receiver.getFirstRow();// 合并区域首行位置
            sheet.getRow(rowNum_receiver).getCell(colIndex_receiver).setCellValue(str_receiver);


            // 第N个合并单元格 : 货物名称 ， 重量
            String str_weight = "";
            if(order.getOrderItems()!=null && order.getOrderItems().size()>0){
                str_weight = order.getOrderItems().get(0).getFullName() + " " + order.getWeight()+"g";
            }else{
                str_weight = "暂无名称";
            }

            CellRangeAddress region_weight = sheet.getMergedRegion(5);
            int colIndex_weight = region_weight.getFirstColumn(); // 合并区域首列位置
            int rowNum_weight = region_weight.getFirstRow();// 合并区域首行位置
            sheet.getRow(rowNum_weight).getCell(colIndex_weight).setCellValue(str_weight);

            // 第N个合并单元格 : 日期

            String str_date = DateUtils.dateStr(new Date());
            CellRangeAddress region_date = sheet.getMergedRegion(4);
            int colIndex_date = region_date.getFirstColumn(); // 合并区域首列位置
            int rowNum_date = region_date.getFirstRow();// 合并区域首行位置
            sheet.getRow(rowNum_date).getCell(colIndex_date).setCellValue(str_date);



            ServletOutputStream sos = response.getOutputStream();

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            wb.write(buffer);
            response.setContentType("application/vnd.ms-excel");
            response.setContentLength(buffer.size());
            response.setHeader("Content-Disposition", "attachment; filename=" + order.getSn()
                    + ".xls");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");
            sos.write(buffer.toByteArray());
            buffer.flush();
            sos.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 购物单打印
     */
    @RequestMapping(value = "/product", method = RequestMethod.GET)
    public String product(Long id, ModelMap model) {
        model.addAttribute("order", orderService.find(id));
        return "/admin/print/product";
    }

    /**
     * 配送单打印
     */
    @RequestMapping(value = "/shipping", method = RequestMethod.GET)
    public String shipping(Long id, ModelMap model) {
        model.addAttribute("order", orderService.find(id));
        return "/admin/print/shipping";
    }

    /**
     * 快递单打印
     */
    @RequestMapping(value = "/delivery", method = RequestMethod.GET)
    public String delivery(Long orderId, Long deliveryTemplateId, Long deliveryCenterId, ModelMap model) {
        DeliveryTemplate deliveryTemplate = deliveryTemplateService.find(deliveryTemplateId);
        DeliveryCenter deliveryCenter = deliveryCenterService.find(deliveryCenterId);
        if (deliveryTemplate == null) {
            deliveryTemplate = deliveryTemplateService.findDefault();
        }
        if (deliveryCenter == null) {
            deliveryCenter = deliveryCenterService.findDefault();
        }
        model.addAttribute("deliveryTemplates", deliveryTemplateService.findAll());
        model.addAttribute("deliveryCenters", deliveryCenterService.findAll());
        model.addAttribute("order", orderService.find(orderId));
        model.addAttribute("deliveryTemplate", deliveryTemplate);
        model.addAttribute("deliveryCenter", deliveryCenter);
        return "/admin/print/delivery";
    }

}